<?php
namespace app\common\controller;
use app\common\model\Admin;
use app\common\model\AuthRule;
use app\common\model\AuthGroupAccess;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use think\facade\Cookie;
use think\Model;

class AdminBase extends Base
{
    protected $noLogin = []; // 不用权限认证和登录的方法
    protected $noAuth = []; // 不用权限认证要登录的方法

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        !$this->checkLogin() && $this->redirect(url('/admin/index/login'));
        !$this->checkAuth() && $this->error('没有权限，请联系管理员');
    }

    /**
     * 登陆验证
     * @return bool
     */
    public function checkLogin()
    {
        if (!is_admin_login() &&
            !in_array($this->request->action(), $this->noLogin)) {
            return false;
        }
        return true;
    }

    /**
     * 权限验证
     * @return bool
     */
    public function checkAuth()
    {
        //砍掉尾部的 JSON
        if(substr($this->request->action(),-5) == '_json'){
            $action = substr($this->request->action(),0,-5);
        }else{
            $action = $this->request->action();
        }
        if (Session::get('admin_auth.admin_id') != '1' &&
            !in_array($this->request->action(), $this->noLogin) &&
            !in_array($this->request->action(), $this->noAuth) &&
            !(new \core\Auth())->check('admin/'
                . to_under_score($this->request->controller()) . '/'
                . $action, Session::get('admin_auth.admin_id'))) {
            return false;
        }
        return true;
    }
}
